package world.liuru.poem.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${path.name}")
    private String pathName;

    @PostMapping("/upload")
    @CrossOrigin
    public String upload(String title,MultipartFile file) throws IOException {
        if (!file.isEmpty()){
            // 上传文件路径
            // String path = request.getServletContext().getRealPath("/uploadFiles/");
            // System.out.println(path);
            String path = pathName;
            // 获得上传文件名
            // String fileName = file.getOriginalFilename();
            File filePath = new File(path + File.separator + title);
            // 如果文件目录不存在，创建目录
            if (!filePath.getParentFile().exists()){
                filePath.getParentFile().mkdirs();
            }
            // 将上传文件保存到一个目标文件中
            file.transferTo(filePath);
            return title;
        }
        return "fail";
    }

    @GetMapping("/download")
    @CrossOrigin
    public ResponseEntity<byte[]> download(@RequestParam("file") String fileName) throws IOException {
        // 下载文件路径
        String path = pathName;
        //构建将要下载的文件对象
        File file = new File(path + File.separator + fileName);
        //设置响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        // 下载显示的文件名，解决中文名称乱码问题
        String downloadFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        //通知浏览器以下载方式(attachment)打开文件
        httpHeaders.setContentDispositionFormData("attachment",downloadFileName);
        // 定义以二进制流数据（最常见的文件下载）的形式下载返回文件数据
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 使用spring mvc框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.OK);
    }

    @GetMapping("/fileList")
    @CrossOrigin
    public List<String> list(){
        String path =  pathName;
        File file = new File(path);
        List<String> arrayList = new LinkedList<>();
        String[] fileNames = file.list();
        for (int i = 0; i < Objects.requireNonNull(fileNames).length; i++){
            if (i > 2){
                break;
            }
            String split = fileNames[i].substring(fileNames[i].indexOf(".") + 1);
            if (split.equals("pdf")){
                arrayList.add(fileNames[i]);
            }
        }
        return arrayList;
    }

}
